package com.subdemo.wordmachine.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.subdemo.wordmachine.domain.Word;
import com.subdemo.wordmachine.domain.req.AddWordReq;
import com.subdemo.wordmachine.mapper.WordMapper;
import com.subdemo.wordmachine.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
public class WordServiceImpl extends ServiceImpl<WordMapper, Word> implements WordService {
    @Autowired
    private WordMapper wordMapper;

    /**
     * 获得一个单词(对象)
     */
    @Override
    public Word getWordById(Integer id) {
        return this.getById(id);
    }

    /**
     * 查询表中所有单词
     */
    @Override
    public List<Word> selectAll() {
        List<Word> list = this.list();
        return list;
    }


    @Override
    public String selectByIdGetCh(Integer id) {
        Word word = this.getById(id);
        return word.getCh();
    }

    @Override
    public String selectByIdGetEn(Integer id) {
        Word word = this.getById(id);
        return word.getEng();
    }

    @Override
    public String selectByIdGetVar(Integer id) {
        Word word = this.getById(id);
        return word.getType();
    }

    /**
     * 表中单词数量
     */
    @Override
    public Integer getWordCount() {
        List<Word> words = selectAll();
        return words.size();
    }

    @Override
    public Boolean deleteById(Integer id) {
        return null;
    }

    @Override
    public Boolean save(AddWordReq addWordReq) {
        return null;
    }

    /**
     * 获得三个选项，其中包括一个正确选项（字符串）
     */
    @Override
    public List<Word> getChooseData(Integer id) {
        List<Word> choose = new ArrayList<>();
        Word word = getWordById(id);
        choose.add(word);
        Integer temp = 0;
        int count = 2;
        for (int i = 0; i < count; i++) {
            Integer incorrectId = getIncorrectAnswer();
            if (!Objects.equals(incorrectId, id) && !Objects.equals(incorrectId,temp)) {
                Word wrongValidity = getWordById(incorrectId);
                choose.add(wrongValidity);
                temp = incorrectId;
            } else
                count++;
        }
        Collections.shuffle(choose);
        return choose;
    }

    /**
     * 检查用户的答案是否正确
     * @param exactId
     * @param chooseId
     * @return
     */
    @Override
    public Boolean checkAnswer(Integer exactId, Integer chooseId) {
        return Objects.equals(chooseId, exactId);
    }

    /**
     * 随机获取1到表中单词数量的随机数
     */
    private Integer getIncorrectAnswer () {
        ArrayList<Integer> ids = new ArrayList<>();
        for (int i = 1; i <= getWordCount(); i++) {
            ids.add(i);
        }
        Collections.shuffle(ids);
        return ids.get(1);
    }


}
